﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

using Dac.DAL;
using Dac.DAL.Repositories;
using Dac.Entities;
using Dac.Code;


namespace Dac.Account
{
    public partial class Login : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginUser.LoggingIn += new LoginCancelEventHandler(LoginUser_LoggingIn);
            LoginUser.LoginError += LoginUser_LoginError;
            LoginUser.Authenticate += LoginUser_Authenticate;

            if (!IsPostBack)
            {
                DoRedirectIfLogin();
            }
        }
               

        private void DoRedirectIfLogin()
        {
            if (User.Identity.IsAuthenticated)
                Response.Redirect("~/Admin/ProductList.aspx", endResponse: true);
        }
        
        private void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
        {
            

            bool validateResult = Membership.ValidateUser(this.LoginUser.UserName, this.LoginUser.Password);
            if (validateResult)
            {
                FormsAuthentication.SetAuthCookie(this.LoginUser.UserName, LoginUser.RememberMeSet);
                Response.Redirect("~/Admin/ProductList.aspx", endResponse: true);
            }
            
            e.Authenticated = false;
        }

        private void LoginUser_LoginError(object sender, EventArgs e)
        {
            LoginUser.FindControl("lblError").Visible = true;
        }

        void LoginUser_LoggingIn(object sender, LoginCancelEventArgs e)
        {
        }
    }
}
